import React, { useContext, useEffect, useRef } from 'react';
import { fabric } from 'fabric';
import EditorWorkspace from './draw/EditorWorkspace';
import { Context } from './store/Context';
import { IEvent } from 'fabric/fabric-impl';
import styles from './workspace.module.less';
// import { useLatest } from 'ahooks';
// import { DrawType } from './assets/toolBar/config';
// import { onFinishPointsChange, groupToEditPolygon } from '@/pages/basicsInfo/booth/projectVisual/utils';

type OffListener = (ev: fabric.IEvent) => void;

/**
 * 画布区域
 * @returns
 */
const Workspace = () => {
    const { canvas, workspace, setState, currentTab, frontImage, backImage, currentImage, currentToolBarTab } = useContext(Context);
    const canvasRef = useRef<HTMLCanvasElement | null>(null);
    const containerRef = useRef<HTMLDivElement | null>(null);
    // 使用 ref 保存最新的 currentImage 和 currentToolBarTab，避免闭包问题
    const currentImageRef = useRef<fabric.Image | null>(currentImage);
    const currentToolBarTabRef = useRef<string>(currentToolBarTab);
    
    // 更新 ref 的值
    useEffect(() => {
        currentImageRef.current = currentImage;
    }, [currentImage]);
    
    useEffect(() => {
        currentToolBarTabRef.current = currentToolBarTab;
    }, [currentToolBarTab]);

    useEffect(() => {
        initCanvas();
    }, []);

    useEffect(() => {
        if (!canvas || !workspace) return;
        canvas.on('mouse:down', clickCanvas); // 画布点击事件
        // canvas.on('selection:created', watchSelectionCreated); // 选择元素事件
        // window.addEventListener('keydown', onKeyDown);
        return () => {
            canvas.off('mouse:down', clickCanvas as OffListener);
            // canvas.off('selection:created', watchSelectionCreated as OffListener); // 选择元素事件
            // window.removeEventListener('keydown', onKeyDown);
        };
    }, [canvas, workspace]);

    /**
     * 点击画布
     * @param e
     * @returns
     */
    const clickCanvas = (e: IEvent<MouseEvent>) => {
        if (!canvas || !workspace) return;
        const target = e.target;
        // 从 ref 中获取最新的值
        const latestCurrentImage = currentImageRef.current;
        const latestCurrentToolBarTab = currentToolBarTabRef.current;
        if (target === null) {
            if (latestCurrentToolBarTab === 'imageEdit' && latestCurrentImage) {
                latestCurrentImage.set({
                    selectable: true,
                    evented: true
                });
                canvas.setActiveObject(latestCurrentImage);
                canvas.renderAll();
            }
        }
    };

    // const watchSelectionCreated = (e: IEvent<MouseEvent>) => {
    //     if (!canvas || !workspace) return;
    //     const target = e.selected?.[0];
    //     if (!target || !workspace || !canvas) return;
    //     if (!workspace.width || !workspace.height) return;
    //     if (target.left === undefined || target.top === undefined) return;
    
    //     setState({ currentImage: target });
    // };

    /**
     * 初始化canvas
     */
    const initCanvas = async () => {
        const domHeight = Math.max(
            document.body.scrollHeight,
            document.documentElement.scrollHeight,
            document.body.offsetHeight,
            document.documentElement.offsetHeight,
            document.body.clientHeight,
            document.documentElement.clientHeight
        );

        const domWidth = Math.max(
            document.body.scrollWidth,
            document.documentElement.scrollWidth,
            document.body.offsetWidth,
            document.documentElement.offsetWidth,
            document.body.clientWidth,
            document.documentElement.clientWidth
        );

        const canvas = new fabric.Canvas(canvasRef.current, {
            fireRightClick: false,
            stopContextMenu: true,
            controlsAboveOverlay: true,
            width: domWidth,
            height: domHeight,
            selection: false,
        });
        const workspace = new EditorWorkspace(canvas);
        setState({ canvas, workspace });
    };

    const handleTabChange = (tab: 'front' | 'back') => {
        if (!canvas) return;
        let currentImage: fabric.Image | null = null;
        if (tab === 'front') {
            currentImage =  frontImage;
        } else {
            currentImage = backImage;
        }

        canvas.discardActiveObject();
        canvas.clear();

        if (currentImage) {
          canvas.add(currentImage);
          if (currentToolBarTab === 'imageEdit') {
            currentImage.set({
                selectable: true,
                evented: true
            });
            canvas.setActiveObject(currentImage);
          } else {
            currentImage.set({
                selectable: false,
                evented: false
            });
          }
        }
        canvas.renderAll();
        setState({ currentTab: tab });
    };

    return (
        <div ref={containerRef} className={styles.container}>
            <div className={styles.tabs}>
                <div className={`${styles.tab} ${currentTab === 'front' ? styles.active : ''}`} onClick={() => handleTabChange('front')}>正面</div>
                <div className={`${styles.tab} ${currentTab === 'back' ? styles.active : ''}`} onClick={() => handleTabChange('back')}>背面</div>
            </div>
            <canvas ref={canvasRef} />
        </div>
    );
};

export default Workspace;
